package net.wicp.tams.duckula.ops.servicesBusi;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.apache.commons.collections.CollectionUtils;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.constant.dic.YesOrNo;
import net.wicp.tams.duckula.common.ZkUtil;
import net.wicp.tams.duckula.common.beans.Task;
import net.wicp.tams.duckula.common.constant.ZkPath;
import net.wicp.tams.duckula.ops.beans.Server;

@Component
@Slf4j
public class Scheduler {

	@Inject
	@Autowired
	private IDuckulaAssit duckulaAssit;

	@PostConstruct
	private void init() {
		runUnStart();
		log.info("int exec sucess");
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
		// 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
		service.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				runUnStart();
			}
		}, 10, 20, TimeUnit.MINUTES);
	}

	/***
	 * 启动异常后失败的文件
	 */
	public void runUnStart() {
		List<String> taskIds = ZkUtil.findSubNodes(ZkPath.tasks);
		for (String taskId : taskIds) {
			checkStartTask(taskId);
		}
	}

	public Result checkStartTask(String taskId) {
		Task task = ZkUtil.buidlTask(taskId);
		if (task != null && task.getRun() == YesOrNo.yes) {// 需要启动
			List<String> locks = ZkUtil.lockIps(taskId);
			if (CollectionUtils.isEmpty(locks)) {// 没有启动
				Server server = duckulaAssit.selServer();
				Result result = duckulaAssit.startTask(taskId, server, true);
				return result;

			}
		}
		return Result.getSuc();
	}

}
